/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package station;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 *
 * @author Gortex
 */
public class LoggerThread extends Thread {

    Logger logger;
    String station;
    String msg;

    public LoggerThread(String name, String msg) {
        station = name;
        logger = new Logger(name);
        this.msg = msg;
    }

    /*
     * Innere Klasse da nur der thread den Logger braucht
     */
    private class Logger extends Thread {

        File log;
        Map<String, String> tempLog;

        public Logger(String logPath) {
            this.log = new File(".//" + logPath + ".log");
            try {
                if (!log.exists()) {
                    log.createNewFile();
                }
            } catch (IOException e) {
                System.out.println("Logging-Dateien konnten nicht erstellt werden.");
            }
            tempLog = new HashMap<String, String>();
        }

        //speichert die uebergebende Message unter dem identifier in den temporaeren Log
        public void logMessage(String identifier, String msg) {
            if (tempLog.containsKey(identifier)) {
                tempLog.put(identifier, tempLog.get(identifier) + msg + "\r\n");
            } else {
                tempLog.put(identifier, new Date(System.currentTimeMillis()).toString() + "  -  Logging fuer " + identifier + " gestartet. " + "\r\n");
                logMessage(identifier, msg);
            }
        }

        //schreibt alle Messages fuer den uebergebenden identifier in die LogDatei und
        //loescht die Messages des identifiers aus dem temporaeren Log
        synchronized public void logToFile(String identifier) {
            if (tempLog.containsKey(identifier)) {
                tempLog.put(identifier, tempLog.get(identifier) + "Login fuer " + identifier + " beendet." + "\r\n\r\n");
                try {
                    FileWriter fw = new FileWriter(log, true);
                    fw.write(tempLog.get(identifier));
                    tempLog.remove(identifier);
                    fw.close();
                } catch (IOException e) {
                    System.out.println("Log konnte nicht in Datei geschrieben werden." + e.getMessage());
                }
            }
        }
    }

    @Override
    public void run() {
        logger.logMessage(station, msg);
        logger.logToFile(station);
    }
}
